using System;
using System.Text;
using System.IO;
using System.IO.Ports;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.USBClient;
using GHIElectronics.NETMF.Hardware;

namespace RFM22b_Transceiver
{
    class VirtualSerialPort
    {
        USBC_CDC cdc;

        string readStrBuff = "";

        public VirtualSerialPort()
        {
            // Check debug interface
            /*if (Configuration.DebugInterface.GetCurrent() ==
                Configuration.DebugInterface.Port.USB1)
                throw new InvalidOperationException("Current debug interface is USB."
                + " It must be changed to something else before proceeding. Refer to "
                + "your platform user manual to change the debug interface.");*/

            // Start CDC
            cdc = USBClientController.StandardDevices.StartCDC();
        }

        public bool Write(string Text)
        {
            if (USBClientController.GetState() == USBClientController.State.Running)
            {
                byte[] buffer = UTF8Encoding.UTF8.GetBytes(Text);
                cdc.Write(buffer, 0, buffer.Length);

                return true;
            }
            else
            {
               return false;
            }
        }

        public string ReadLine()
        {
            if (USBClientController.GetState() == USBClientController.State.Running)
            {
                int bcount = 256;
                int brPos = 0;
                byte[] buffer = new byte[bcount];
                string retStr;

                bcount = cdc.Read(buffer, 0, bcount);

                readStrBuff += new string(UTF8Encoding.UTF8.GetChars(buffer));

                brPos = readStrBuff.IndexOf("\r\n", 0);

                if (brPos > 0)
                {
                    retStr = readStrBuff.Substring(0, brPos);
                    readStrBuff = readStrBuff.Substring(brPos + 2);
                }
                else
                {
                    retStr = "";
                }

                return retStr;
            }
            else
            {
                return "";
            }
        }
    }
}
